﻿using LightCAD.Core;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.Drawing
{
    public class InElementsInputer : Inputer
    {
        private LcElement inputElement;
        private Vector2d? inputp;
        private string option;
        private ElementCollection Elements;
        private Matrix3d Matrix3;
        protected ViewportRuntime vportRt;
        public InElementsInputer(DocumentRuntime docRt, ElementCollection elements, Matrix3d matrixs = new Matrix3d()) : base(docRt)
        {
            vportRt = this.docRt.DrawingEditRt.ActiveViewportRt;
            Elements = elements;
            Matrix3= matrixs;
        }
        public async Task<InputResult> Execute(string prompt)
        {
            inputp = null;
            option = null;
            this.Reset();
            this.AttachEvents();
            Prompt(prompt);
            await WaitFinish();
            this.DetachEvents();
            if (this.isCancelled)
                return null;
            else
            {
                return new InputResult(inputElement, option);
            }
        }

        protected override void OnViewportMouseDown(MouseEventRuntime e)
        {
            this.inputp = e.Location.ToVector2d();
            var wcsp = this.vportRt.ConvertScrToWcs(e.Location.ToVector2d());
            var wsize = this.vportRt.ConvertScrToWcs(Constants.SelectBoxSize);

            var hitResult= InputUtils.ElementsSelect(Elements, wcsp, wsize);
            //var hitResult = docRt.Action.HitSelect(this.docRt.Document.ModelSpace, wcsp, wsize);
            if (hitResult != null && hitResult.Item1 != null)
            {
                inputElement = hitResult.Item1;
                docRt.CommandCtrl.WriteInfo(docRt.CommandCtrl.GetPrompt());
                this.Finish();
            }
        }

        protected override void OnInputBoxKeyDown(KeyEventRuntime e)
        {
            base.OnInputBoxKeyDown(e);
            if (e.KeyCode == 13 || e.KeyCode == 32)//Keys.Enter
            {
                var text = docRt.CommandCtrl.GetInputText().Trim();
                docRt.CommandCtrl.SetInputText(string.Empty);
                //TODO:检查可以输入的字符
                this.inputp = InputUtils.ParsePoint(text);
                if (this.inputp == null)
                {
                    this.option = text;
                    if (this.option == string.Empty)
                    {
                        this.option = "";
                    }
                }
                this.Finish();
            }


        }
    }
}
